<?php
namespace Cmf\Controllers;

use Cmf\Models\Role;
use Cmf\Forms\RoleForm;
use Phalcon\Http\Response;

/**
 * 角色控制器
 */
class RoleController extends BaseController
{
	// 角色列表
	public function indexAction()
	{
		$currentPage = $this->request->getQuery('page','int');

		$list = Role::find(array(
			'order'   => 'id DESC',
			'columns' => 'id,title,description,status',
		));

		$paginator = new \Phalcon\Paginator\Adapter\Model(
			array(
				'data'  => $list,
				'limit' => 15,
				'page'  => $currentPage,
			)
		);

		$page = $paginator->getPaginate();
		$this->view->page = $page;
	}

	// 新增角色页面
	public function newAction()
	{
		$form = new RoleForm();
		$this->view->form = $form;
	}

	// 新增角色操作
	public function createAction()
	{
		if($this->request->isPost()) {
			$Role = new Role();
			$form = new RoleForm();

			if($form->isValid($this->request->getPost()) === false) {
				foreach($form->getMessages() as $key => $message) {
					$this->flash->error($message);
				}

				return $this->dispatcher->forward(['controller' => 'role','action' => 'new']);
			}

			if(!$Role->create($this->request->getPost())) {
				foreach($Role->getMessages() as $message) {
					$this->flash->error($message);
				}

				return $this->dispatcher->forward(['controller' => 'role','action' => 'new']);
			}

			$this->flash->success('新增角色成功');

			return $this->response->redirect('role/index');
		}
	}

	//角色编辑页面
	public function editAction()
	{
		$role = Role::findFirstById($this->request->getQuery('id'));
		$form = new RoleForm($role,'edit');
		$this->view->form = $form;
	}

	//角色编辑操作
	public function updateAction()
	{
		if($this->request->isPost()) {
			$Role = new Role();
			$form = new RoleForm();

			if($form->isValid($this->request->getPost()) === false) {
				foreach($form->getMessages() as $key => $message) {
					$this->flash->error($message);
				}

				return $this->dispatcher->forward(['controller' => 'role','action' => 'new']);
			}

			if(!$Role->save($this->request->getPost())) {
				foreach($Role->getMessages() as $message) {
					$this->flash->error($message);
				}

				return $this->dispatcher->forward(['controller' => 'role','action' => 'new']);
			}

			$this->flash->success('编辑角色成功');

			return $this->response->redirect('role/index');
		}
	}

	//删除角色操作
	public function deleteAction()
	{
		$this->view->disable();

		$role = Role::findFirstById($this->request->getPost('id'));
		$response = new Response();

		if (!$role) {
			$response->setContent(json_encode(['message' => '角色不存在']));

			return $response;
		}

		if (!$role->delete()) {
			foreach ($role->getMessage() as $message) {
				$this->flash->error($message);
			}
			$response->setContent(json_encode(['message' => '角色删除失败']));

			return $response;
		}

		$response->setContent(json_encode(['message' => '角色菜单成功', 'id' => $this->request->getPost('id') ]));

		return $response;
	}
}
